//
//  JobImageListViewController.swift
//  ezyform
//
//  Created by MoennigQ on 28/2/19.
//  Copyright © 2019 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
import Photos
import PhotosUI
import MBProgressHUD
import SnapKit
import CoreServices
import PDFKit
enum ChecklistFileType: Int{
    case image = 0
    case pdf
}
enum PhotoSource: String{
    case takePhoto = "photo"//拍照，上传API时亦可传数字2
    case autoRecognition = "auto_recognition"//selfie自动识别，上传API时亦可传数字5
    case selectFromPhotoLibrary = "photo_album"//相册，上传API时亦可传数字1
}
enum CheckListImageFromType: String{
    case takePhoto = "Take Photo"
    case chooseFromLibrary = "Choose From Library"
    case uploadPdf = "Upload Files (PDF)"
    case addElectricialCertificate = "Generate Electrician Table"//"Add Electricial Certificate"
}
class JobImageListViewController: BaseViewController {
    var model: PVDDetailModel!
    let checkLocationServciceForChecklist: String = "\(JobDetailModelHelper.shared.jobDetailModel.pvd_id)-Checklist-CheckLocation"
    let customView = JobImageListView()
    var bottomOperateList = [CellModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        if let data = self.model.pvd_checklists.first(where: {$0.id == JobDetailModelHelper.shared.checklistModel.id}){
            JobDetailModelHelper.shared.checklistModel = data
            JobDetailModelHelper.shared.checklistModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
        }
        self.initUI()
        //预览图片或pdfe
        self.customView.previewClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            
            let iModel: CheckListImageDBModel = JobDetailModelHelper.shared.checklistModel.images[row]
            let imagePath = iModel.image
            if imagePath.contains(APPConfig.PDFSuffix){
                let vc = AttachmentViewController()
                vc.attchmentType = .ChecklistPDF
                vc.attachmentURL = imagePath
                vc.attachmentTitle = ""
                strongSelf.navigationController?.pushViewController(vc, animated: false)
            }else{
                let (imagesList, index) = strongSelf.getAllImagePathAndIndex(iModel)
                if imagesList.count > 0 {
                    let vc = BrowseImageViewController()
                    vc.imagesArray = imagesList
                    vc.currentIndex = index
                    strongSelf.navigationController?.pushViewController(vc,animated: true)
                }
            }
        }
        //删除图片或pdf
        self.customView.deleteClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            //处理上传完后需重新设置数据
            guard let data = strongSelf.model.pvd_checklists.first(where: {$0.id == JobDetailModelHelper.shared.checklistModel.id}) else {return}
            JobDetailModelHelper.shared.checklistModel = data
            JobDetailModelHelper.shared.checklistModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
            guard row < JobDetailModelHelper.shared.checklistModel.images.count else {return}
            let imageModel = JobDetailModelHelper.shared.checklistModel.images[row]
            let imagePath = imageModel.image
            let pdfFlag = imagePath.contains(APPConfig.PDFSuffix)
            //image没在上传中，才可以做删除；如果在上传过程中，则不能进行删除（会导致数据错乱）
            if DBManager.shared.checkIfImageUploadingByRecordAt(imageModel) {
                Tool().showAlertViewWithOneBtn(message: "The current \(pdfFlag ? "file" : "image") is being uploaded and cann't be deleted.")
            }else{
                
                Tool().showAlertViewWithTwoBtns(title:  "Delete \(pdfFlag ? "File" : "Image")", message: "Are you sure to delete this \(pdfFlag ? "file" : "image")?",yesClosure: {
                    if imagePath.contains("http"){//server
                        JobDetailModelHelper.shared.checklistModel.localDeletedImages.append(imageModel)//只有已经上传的，才增加到localDeletedImages；本地的数据是直接删除
                        imageModel.pvd_id = strongSelf.model.id
                        imageModel.checklist_id = JobDetailModelHelper.shared.checklistModel.id
                        imageModel.title = JobDetailModelHelper.shared.checklistModel.title
                        imageModel.oper_type = DataOperType.Del.rawValue
                        imageModel.id = imageModel.id
                        DBManager.shared.insertChecklistImages(model: imageModel)
                        //有网络才能请求删除删除
                        if Connectivity.isConnectedToInternet {
                            ModelViewUtil.shared.showLoadingView("Deleting...")
                            if imageModel.checklist_id == ChecklistFixedId.nocAttachment.rawValue || imageModel.checklist_id == ChecklistFixedId.otherAttachment.rawValue{
                                UploadManager.shared.deleteAttachment(imageModel: imageModel) { successFlag in
                                    ModelViewUtil.shared.hideLoadingView()
                                }
                            }else{
                                UploadManager.shared.uploadChecklistImage(imageModel: imageModel) { successFlag in
                                    ModelViewUtil.shared.hideLoadingView()
                                }
                            }
                            
                        }
                    }else{//delete 本地数据
                        DBManager.shared.deleteChecklistImageData(model: imageModel)
                    }
                    //删除当前checklist image中的数据，并触发所有刷新
                    JobDetailModelHelper.shared.checklistModel.images.remove(at: row)
                    if let index = strongSelf.model.pvd_checklists.firstIndex(where: {$0.id == JobDetailModelHelper.shared.checklistModel.id}){
                        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index] = JobDetailModelHelper.shared.checklistModel
                        JobDetailModelHelper.shared.jobDetailModel.broadCastChecklistData()
                    }
                })
            }
        }
        //进入Checklist获取一次定位信息
        if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
            let selfiFlag = [ChecklistFixedId.preInstall.rawValue,ChecklistFixedId.midInstall.rawValue,ChecklistFixedId.testAndCommission.rawValue].contains(JobDetailModelHelper.shared.checklistModel.id )
            Tool().requestCurrentLocation(selfiFlag ? .continous : .single)//三个自拍才需要开启持续定位，尽早获取当前位置的精确定位
        }
    }
    private func initUI(){
        //top view
        self.view = self.customView
        self.customView.setTitleInfo(JobDetailModelHelper.shared.checklistModel.title)
        
        //1.set top data
        self.customView.setData()
        self.bottomOperateList = self.getOperationList()
        self.customView.initBottomView(self.bottomOperateList)
        //拍照
        self.customView.takePhotoClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.takePhoto()
        }
        //选择图库
        self.customView.choosePictureClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.selectFromPhotosLibrary()
        }
        //多选按钮Add attach们额头
        self.customView.addAttachmentClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.addAttachment()
        }
    }
    
    //MARK: 获取底部操作有几个菜单，少于三个直接显示在底部，大于等于三个只显示Add Attachment
    private func getOperationList()->[CellModel]{
        var cellList = [CellModel]()
        if JobDetailModelHelper.shared.checklistModel.is_selfie_flag {//自拍只有take photo一个操作
            cellList.append(CellModel(title: CheckListImageFromType.takePhoto.rawValue))
        }else{
            if JobDetailModelHelper.shared.checklistModel.is_show_photos{//显示拍照，选择相册的按钮
                cellList.append(CellModel(title: CheckListImageFromType.takePhoto.rawValue))
                cellList.append(CellModel(title: CheckListImageFromType.chooseFromLibrary.rawValue))
            }else{
                cellList.append(CellModel(title: CheckListImageFromType.takePhoto.rawValue))
            }
            cellList.append(CellModel(title: CheckListImageFromType.uploadPdf.rawValue))
            //CES
            if JobDetailModelHelper.shared.checklistModel.id == ChecklistFixedId.certificateOfElectricalSafety.rawValue{
                //电工表单模板不为空，且当前checklist中的actions中的electrical 是true
                let electricalTemplate = self.model.electrical_template
                let electricalFlag = JobDetailModelHelper.shared.checklistModel.actions.electrical
                if electricalTemplate != "" && electricalFlag{
                    cellList.append(CellModel(title: CheckListImageFromType.addElectricialCertificate.rawValue))
                }
            }
        }
        return cellList
    }
    //MARK: 多选按钮Add attachment
    fileprivate func addAttachment(){
        let actionSheetView = CustomActionSheet(title: R.string.localizable.addDocument(), aCellArray: self.bottomOperateList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            switch strongSelf.bottomOperateList[row].title {
            case CheckListImageFromType.takePhoto.rawValue:
                strongSelf.takePhoto()
            case CheckListImageFromType.chooseFromLibrary.rawValue:
                strongSelf.selectFromPhotosLibrary()
            case CheckListImageFromType.uploadPdf.rawValue:
                if #available(iOS 14.0, *) {
                    let vc = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pdf])
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                } else {
                    let vc = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: UIDocumentPickerMode.import)
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                }
            case CheckListImageFromType.addElectricialCertificate.rawValue:
                strongSelf.addElectricialCertificate()
            default:
                break
            }
        }, aCancelClosure: nil)
        self.navigationController?.view.addSubview(actionSheetView)
    }
    private func addElectricialCertificate(){
        let vc = ElectricalCertificateViewController()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    private func takePhoto(){
        if JobDetailModelHelper.shared.checklistModel.lodged_check{//需要GPS定位信息，友好提示，但是不强制
            let checkChecklistFlag = UserDefaults.standard.value(forKey: checkLocationServciceForChecklist) as? Bool ?? false
            if checkChecklistFlag {//弹出提示过就不再提示
                self.openTakePhotoVC()
            }else{//没提示过，检查需要什么提示
                if CLLocationManager.locationServicesEnabled() == false {//设备未开启GPS功能
                    self.showRequstGPSAlertView()
                }else {//设备已开启GPS功能
                    let status = CLLocationManager.authorizationStatus()
                    if status == .denied || status == .restricted {
                        self.showRequstGPSAlertView()
                    }else{
                        self.openTakePhotoVC()
                    }
                }
            }
        }else{
            self.openTakePhotoVC()
        }
    }
    //MARK: - 检查是否是自拍checklist，如果是要检查必填项顺序，否则直接拍照
    private func openTakePhotoVC(){
        //只有这三个自拍才做提示
        if JobDetailModelHelper.shared.checklistModel.is_selfie_flag {
            InstallationDetailVCHelper.shared.checkOrderChecklist( model: self.model, checklistModel: JobDetailModelHelper.shared.checklistModel) {
                self.toTakePhotoVC()
            }
        }else{
            toTakePhotoVC()
        }
    }
    //MARK: - 拍照
    private func toTakePhotoVC(){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.async {
                if status {
                    if JobDetailModelHelper.shared.checklistModel.is_selfie_flag {
                        let vc = FaceDetectSelfieVC()
                        vc.naviTitle = JobDetailModelHelper.shared.checklistModel.title
                        vc.takeSelfeiClosure = {(image, selfieSource) in
                            //处理并保存图片
                            PhotosManager.shared.dealPhotoFromTakePhoto(originImage: image,photoSource: selfieSource)
                        }
                        vc.modalPresentationStyle = .overFullScreen
                        self.present(vc, animated: true, completion: nil)
                    }else{
                        let vc = TakePhotoViewController()
                        vc.photosCnt = JobDetailModelHelper.shared.checklistModel.images.count
                        vc.naviTitle = JobDetailModelHelper.shared.checklistModel.title
                        vc.takePhotoClosure = {image in
                            //处理并保存图片
                            PhotosManager.shared.dealPhotoFromTakePhoto(originImage: image,photoSource: .takePhoto)
                        }
                        //在Take photo 中点击相册
                        vc.selectPhotosFromLibraryClosure = { assert in
                            if JobDetailModelHelper.shared.checklistModel.images.count <= 0 {
                                JobDetailModelHelper.shared.checklistModel.answered_at = DateUtil().getCurrentDatetime()
                            }
                            PhotosManager.shared.addImageFromPhotosForPVDJob(assert, lodgedCheck: JobDetailModelHelper.shared.checklistModel.lodged_check)
                        }
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    //
    
    //MARK: - 如果没有开启GPS给与提示
    private func showRequstGPSAlertView(){
        let view = ChecklistRequestGPSAlertView()
        view.settingsBtnClosure = {
            //URL(string:"App-Prefs:root=Privacy&path=LOCATION")是私有API, 不能使用，审核会被拒的
            if  UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:],completionHandler: nil)
            }
            self.saveRequestGPSAlertStatus(view.checkBtn.tag)
        }
        view.okBtnClosure = {
            self.saveRequestGPSAlertStatus(view.checkBtn.tag)
            self.openTakePhotoVC()
        }
        view.moreInfoBtnClosure = {
            let vc = AttachmentViewController()
            vc.attchmentType = .OtherLink
            vc.attachmentURL = "http://www.cleanenergyregulator.gov.au/About/Pages/News%20and%20updates/NewsItem.aspx?ListId=19b4efbb-6f5d-4637-94c4-121c1f96fcfe&ItemId=915"
            vc.attachmentTitle = "GreenDeal"
            self.navigationController?.pushViewController(vc, animated: false)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 只提示一次
    private func saveRequestGPSAlertStatus(_ tag: Int )  {
        if tag == 1 {
            UserDefaults.standard.set(true, forKey: checkLocationServciceForChecklist)
        }
    }
    //MARK: - 选择相册
    func selectFromPhotosLibrary(){
        PhotosManager.shared.initData(vc: self, maxCount: 10, closure: { pHAssert, errmsg in
            if let _ = errmsg{
                Tool().showAlertViewWithOneBtn(message: errmsg!)
            }else if let data = pHAssert as? PHAsset{
                if JobDetailModelHelper.shared.checklistModel.images.count <= 0 {
                    JobDetailModelHelper.shared.checklistModel.answered_at = DateUtil().getCurrentDatetime()
                }
                PhotosManager.shared.addImageFromPhotosForPVDJob(data,lodgedCheck: JobDetailModelHelper.shared.checklistModel.lodged_check)
            }
        }).getPhotos(assertFLag: true)
    }
    //MARK: - 获取所有的Image类型（过滤掉pdf），及当前选择行的index
    private func getAllImagePathAndIndex(_ selImageModel: CheckListImageDBModel)->([BrowseImageData], Int){
        //1.过滤出来所有的图片，不要pdf
        let resultList: [BrowseImageData] = JobDetailModelHelper.shared.checklistModel.images.filter({!$0.image.contains(APPConfig.PDFSuffix)}).map {BrowseImageData(image: $0.image)}
        
        //2.获取当前点击的index
        let index = resultList.firstIndex {  imageModel in
            if imageModel.image == selImageModel.image{
                return true
            }else{
                return false
            }
        }
        return (resultList, index ?? 0)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    deinit{
        LocationManager.shared.releaseManager()
        DebugLog("deinit")
    }
}
extension JobImageListViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let firstUrl = urls.first else {return}
        //startAccessingSecurityScopedResource()返回true的话，和stopAccessingSecurityScopedResource成对出现
        let urlAuthrized = firstUrl.startAccessingSecurityScopedResource()
        //获取授权
        //通过文件协调器读取文件地址
        var fileData: Data?
        let fileCoordinator = NSFileCoordinator()
        fileCoordinator.coordinate(readingItemAt: firstUrl, options: [.withoutChanges], error: nil) { (newUrl) in
//            let fileName = newUrl.lastPathComponent
            //读取文件协调器提供的新地址里的数据
            fileData = try? Data.init(contentsOf: newUrl, options: [.mappedIfSafe])
            if let data = fileData {
                PhotosManager.shared.savePVDImageData(data as NSData, photoModel: ChecklistPhotoModel(),fileType: .pdf, photoSource: PhotoSource.selectFromPhotoLibrary)
                //获取到数据
//                if let img = self.pdfThumbnail(newUrl), let data = img.jpegData(compressionQuality: 0.5){
//                    self.saveImageData(data as NSData, photoModel: ChecklistPhotoModel())
//                }
            }
        }
        //
        if urlAuthrized {
            firstUrl.stopAccessingSecurityScopedResource()
        }
    }
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        self.dismiss(animated: true)
    }
}

